#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "prop.h"
#include "logger.h"

static FILE *logger;
static int debug_flag;
static int info_flag;
static int warning_flag;
static int error_flag;

int log_init(const char *log_cfg) {
	struct prop propObj;
	propObj.props = NULL;
	//printf("load file %s\n",log_cfg);
	int ret = read_prop(log_cfg, &propObj);
	if(ret != 0){
		return ret;
	}
	//printf("logcnf %s\n",log_cfg);
	const char *lvl = get_prop(&propObj, "logger.lvl");
	//printf("12 %s\n",lvl);
	if (strcmp(lvl, "debug") == 0) {
		debug_flag = 1;
		info_flag = 1;
		warning_flag = 1;
		error_flag = 1;
	} else if (strcmp(lvl, "info") == 0) {
		debug_flag = 0;
		info_flag = 1;
		warning_flag = 1;
		error_flag = 1;
	} else if (strcmp(lvl, "warning") == 0) {
		debug_flag = 0;
		info_flag = 0;
		warning_flag = 1;
		error_flag = 1;
	} else if (strcmp(lvl, "error") == 0) {
		debug_flag = 0;
		info_flag = 0;
		warning_flag = 0;
		error_flag = 1;
	} else {
		return 1;
	}

	const char *file_path = get_prop(&propObj, "logger.out");
	logger = fopen(file_path, "a");

//printf("555555555555555555555555%s\n",file_path);
	if (logger == NULL) { //printf("err at open file");
		return 1;
	}
	return 0;
}

int could_debug() {
	return debug_flag;
}
int could_info() {
	return info_flag;
}
int could_warning() {
	return warning_flag;
}
int could_error() {
	return error_flag;
}

int debug(const char *file, const char *func, u_int32_t line, const char *msg) {
	fprintf(logger,"d %s:%s:%d %s\n",file,func,line,msg);
	return 0;
}
int info(const char *file, const char *func, u_int32_t line, const char *msg) {
fprintf(logger,"i %s:%s:%d %s\n",file,func,line,msg);
	return 0;
}
int warning(const char *file, const char *func, u_int32_t line, const char *msg) {
fprintf(logger,"w %s:%s:%d %s\n",file,func,line,msg);
	return 0;
}
int error(const char *file, const char *func, u_int32_t line, const char *msg) {
fprintf(logger,"e %s:%s:%d %s\n",file,func,line,msg);
	return 0;
}
